//使用
//<field name="department_id"  widget="treeMany2One" parent_field="parent_id"/>
//parent_field默认 'parent_id'

odoo.define('widget_TreeMany2One_id', function (require) {
    "use strict";

    var core = require('web.core');
    var AbstractField = require('web.AbstractField');
    var fieldRegistry = require('web.field_registry');
    var _lt = core._lt;
    var TreeMany2One_id = AbstractField.extend({
        description: _lt("Many2one"),
        supportedFieldTypes: ['many2one'],
        tagName: 'div',
        template: "TreeOne2ManyID",
        events: _.extend({}, AbstractField.prototype.events, {
            'focusout input': '_onInputFocusout',
            'keyup input': '_onInputKeyup',
            'click a': '_onchange',
        }),

        init: function () {
            this.treeSelid = _.uniqueId('treeSel');
            this.treemenuContentid = _.uniqueId('treemenuContent');
            this.treeDemoid = _.uniqueId('treeDemo');
            this.treeIid = _.uniqueId('treeI');
            this._super.apply(this, arguments);
            this._set_tree();
        },

        _get_data: function () {
            if (this.$('#' + this.treeSelid).attr("data")) {
                return parseInt(this.$('#' + this.treeSelid).attr("data"))
            } else {
                return null
            }
        },

        _doAction: function () {
            if (!this.isDestroyed()) {
                var tree_data = {
                    display_name: this.$('#' + this.treeSelid).val(),
                    id: this._get_data()
                }
                return this._setValue(tree_data);

            }
        },
        _onchange: function () {
            this._doAction()
        },

        hideMenu1: function () {
            this.$('#' + this.treemenuContentid).fadeOut("fast");
            $("body").unbind("mousedown", this.onBodyDown1);
        },
        onBodyDown1: function () {
            if (!(event.target.id == "menuBtn" || event.target.id == self.treemenuContentid || $(event.target).parents('#' + self.treemenuContentid).length > 0)) {
                self.hideMenu1();
            }
        },
        beforeClick: function (treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(self.treeDemoid)
                var check = (treeNode && !treeNode.isParent);
                if (!check) {
                    zTree.expandNode(treeNode);
                }
                return check;
        },
        onClick: function (e,treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj(self.treeDemoid);
            var nodes = zTree.getSelectedNodes();
            var v = "";
            var v_id = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].name + ",";
                if (nodes[i].id !== null) {
                    v_id += nodes[i].id.toString() + ","
                } else {
                    v_id += null + ","
                }

            }
            if (v.length > 0) v = v.substring(0, v.length - 1);
            if (v_id.length > 0) v_id = v_id.substring(0, v_id.length - 1);
            var cityObj = $('#' + self.treeSelid);
            cityObj.val(v)
            cityObj.attr('data', v_id)
            self.hideMenu1();
        },
        _renderReadonly: function () {
            this.$('#' + this.treeSelid).click()
            this.$('#' + this.treeSelid).attr("readonly", "readonly")
            this.$('#' + this.treeSelid).css("border", "none")
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            }
            this._super.apply(this, arguments);

        },
        _renderEdit: function () {
            self = this
            if (this.field.required == true || this.attrs.required == 'True' || this.attrs.required == '1'){
                this.$('#' + this.treeSelid).css('background-color','#D2D2FF')
                this.$('#' + this.treeIid).css({'border-top':'0.3em solid','border-left':'0.3em solid transparent','border-right':'0.3em solid transparent'})

            }
            this.$el[0].querySelector('#' + this.treeSelid).onclick = self._inputonclick.bind(self)
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            }
            this._super.apply(this, arguments);

        },
        _set_tree: function () {
            self = this;
            this.tree_setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeClick: this.beforeClick,
                    onClick: self.onClick.bind(self)
                }
            };
            this.is_open = false
        },
        _bind_data: function (search_name) {
            var tree_setting = this.tree_setting
            var tree_zNodes;
            var p_field = 'parent_id'
            if (self.__node.attrs.parent_field) {
                p_field = self.__node.attrs.parent_field
            }
            self._rpc({
                model: self.field.relation,
                method: 'search_read',
                args: [[['name', 'ilike', search_name]], ['id', 'name', p_field]],
                limit: 5000,

            }).then(function (result) {
                var tree_zNodes_m = result.map(r => {
                    return {id: r.id, pId: r[p_field][0], name: r.name, open: self.is_open}
                })
                tree_zNodes = tree_zNodes_m
                $(document).ready(function () {
                    $.fn.zTree.init($('#' + self.treeDemoid), tree_setting, tree_zNodes);
                    var _height = $('.o_form_sheet').offset().top + $('.o_form_sheet').height() - self.$('#' + self.treeSelid).offset().top;
                    var _tree_height = 27+(18*tree_zNodes.length)
                    if(_tree_height>300){
                        _tree_height = 300
                    }
                    if (_height < _tree_height) {
                        $('.o_form_sheet').height($('.o_form_sheet').height() + (_tree_height - _height))
                    }
                });
            });
        },
        _onInputKeyup: function () {
            if($('#' + this.treeSelid).val() === ''){
                var cityObj = $('#' + self.treeSelid);
                cityObj.val('')
                cityObj.attr('data', null)
                this._doAction()
            }
            this._bind_data(this.$('#' + this.treeSelid).val())
            self.$('#' + this.treemenuContentid).slideDown("fast");
            $("body").bind("mousedown", self.onBodyDown1);
        },
        _onInputFocusout: function () {
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            } else {
                this.$('#' + this.treeSelid).val('');
            }
        },
        _inputonclick: function () {
            self = this
            var treewidth = self.$('#' + this.treeSelid).width()
            self.$('#' + this.treemenuContentid).width(treewidth)
            self.$('#' + this.treemenuContentid).removeClass("o_field_widget");
            if (self.$('#' + this.treemenuContentid).is(':hidden')) {
                self._bind_data('')
                self.$('#' + this.treemenuContentid).slideDown("fast");
                $("body").bind("mousedown", self.onBodyDown1);
            } else {
                self.hideMenu1();
            }
        },

    });

    var TreeMany2One_all = TreeMany2One_id.extend({
        _set_tree: function () {
            self = this
            this.tree_setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: self.onClick.bind(self)
                }
            };
            this.is_open = false
        },
    });

    var TreeMany2One_open = TreeMany2One_id.extend({
        _set_tree: function () {
            self = this
            this.tree_setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeClick: this.beforeClick,
                    onClick: self.onClick.bind(self)
                }
            };
            this.is_open = true
        },
    });

    var TreeMany2One_all_open = TreeMany2One_id.extend({
        _set_tree: function () {
            self = this
            this.tree_setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: self.onClick.bind(self)
                }
            };
            this.is_open = true
        },
    });

    var TreeMany2One_list = AbstractField.extend({
        description: _lt("Many2one"),
        supportedFieldTypes: ['many2one'],
        tagName: 'div',
        template: "TreeOne2ManyIDList",
        events: _.extend({}, AbstractField.prototype.events, {
            'focusout input': '_onInputFocusout',
            'keyup input': '_onInputKeyup',
            'click a': '_onchange',
        }),
        cssLibs: ['/sys_tools/static/src/css/zTreeStyleList.css'],

        init: function () {
            this.treeSelid = _.uniqueId('treeSel');
            this.treemenuContentid = _.uniqueId('treemenuContent');
            this.treeDemoid = _.uniqueId('treeDemo');
            this.treeIid = _.uniqueId('treeI');
            this._super.apply(this, arguments);
            this._set_tree();
        },

        _get_data: function () {
            if (this.$('#' + this.treeSelid).attr("data")) {
                return parseInt(this.$('#' + this.treeSelid).attr("data"))
            } else {
                return null
            }
        },

        _doAction: function () {
            if (!this.isDestroyed()) {
                var tree_data = {
                    display_name: this.$('#' + this.treeSelid).val(),
                    id: this._get_data()
                }
                return this._setValue(tree_data);

            }
        },
        _onchange: function () {
            this._doAction()
        },

        hideMenu1: function () {
            this.$('#' + this.treemenuContentid).fadeOut("fast");
            $("body").unbind("mousedown", this.onBodyDown1);
        },
        onBodyDown1: function () {
            if (!(event.target.id == "menuBtn" || event.target.id == self.treemenuContentid || $(event.target).parents('#' + self.treemenuContentid).length > 0)) {
                self.hideMenu1();
            }
        },
        beforeClick: function (treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(self.treeDemoid)
                var check = (treeNode && !treeNode.isParent);
                if (!check) {
                    zTree.expandNode(treeNode);
                }
                return check;
        },
        onClick: function (e,treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj(self.treeDemoid);
            var nodes = zTree.getSelectedNodes();
            var v = "";
            var v_id = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].name + ",";
                if (nodes[i].id !== null) {
                    v_id += nodes[i].id.toString() + ","
                } else {
                    v_id += null + ","
                }

            }
            if (v.length > 0) v = v.substring(0, v.length - 1);
            if (v_id.length > 0) v_id = v_id.substring(0, v_id.length - 1);
            var cityObj = $('#' + self.treeSelid);
            cityObj.val(v)
            cityObj.attr('data', v_id)
            self.hideMenu1();
        },
        _renderReadonly: function () {
            this.$('#' + this.treeSelid).click()
            this.$('#' + this.treeSelid).attr("readonly", "readonly")
            this.$('#' + this.treeSelid).css("border", "none")
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            }
            this._super.apply(this, arguments);

        },
        _renderEdit: function () {
            self = this
            if (this.field.required == true || this.attrs.required == 'True' || this.attrs.required == '1'){
                this.$('#' + this.treeSelid).css('background-color','#D2D2FF')
                this.$('#' + this.treeIid).css({'border-top':'0.3em solid','border-left':'0.3em solid transparent','border-right':'0.3em solid transparent'})

            }
            this.$el[0].querySelector('#' + this.treeSelid).onclick = self._inputonclick.bind(self)
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            }
            this._super.apply(this, arguments);

        },
        _set_tree: function () {
            self = this;
            this.tree_setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeClick: this.beforeClick,
                    onClick: self.onClick.bind(self)
                }
            };
            this.is_open = false
        },
        _bind_data: function (search_name) {
            var tree_setting = this.tree_setting
            var tree_zNodes;
            var p_field = 'parent_id'
            if (self.__node.attrs.parent_field) {
                p_field = self.__node.attrs.parent_field
            }
            self._rpc({
                model: self.field.relation,
                method: 'search_read',
                args: [[['name', 'ilike', search_name]], ['id', 'name', p_field]],
                // args: [self.attrs.domain, ['id', 'name', p_field]],
                limit: 5000,

            }).then(function (result) {
                var tree_zNodes_m = result.map(r => {
                    return {id: r.id, pId: r[p_field][0], name: r.name, open: self.is_open}
                })
                tree_zNodes = tree_zNodes_m
                $(document).ready(function () {
                    $.fn.zTree.init($('#' + self.treeDemoid), tree_setting, tree_zNodes);
                    var _height = $('.o_form_sheet').offset().top + $('.o_form_sheet').height() - self.$('#' + self.treeSelid).offset().top;
                    var _tree_height = 27+(18*tree_zNodes.length)
                    if(_tree_height>300){
                        _tree_height = 300
                    }
                    if (_height < _tree_height) {
                        $('.o_form_sheet').height($('.o_form_sheet').height() + (_tree_height - _height))
                    }
                });
            });
        },
        _onInputKeyup: function () {
            if($('#' + this.treeSelid).val() === ''){
                var cityObj = $('#' + self.treeSelid);
                cityObj.val('')
                cityObj.attr('data', null)
                this._doAction()
            }
            this._bind_data(this.$('#' + this.treeSelid).val())
            self.$('#' + this.treemenuContentid).slideDown("fast");
            $("body").bind("mousedown", self.onBodyDown1);
        },
        _onInputFocusout: function () {
            if (this.value) {
                this.$('#' + this.treeSelid).val(this.value.data.display_name);
            } else {
                this.$('#' + this.treeSelid).val('');
            }
        },
        _inputonclick: function () {
            self = this
            var treewidth = self.$('#' + this.treeSelid).width()
            self.$('#' + this.treemenuContentid).width(treewidth)
            self.$('#' + this.treemenuContentid).removeClass("o_field_widget");
            if (self.$('#' + this.treemenuContentid).is(':hidden')) {
                self._bind_data('')
                self.$('#' + this.treemenuContentid).slideDown("fast");
                $("body").bind("mousedown", self.onBodyDown1);
            } else {
                self.hideMenu1();
            }
        },

    });



    fieldRegistry.add('treeMany2One', TreeMany2One_id);
    fieldRegistry.add('treeMany2OneAll', TreeMany2One_all);
    fieldRegistry.add('treeMany2OneOpen', TreeMany2One_open);
    fieldRegistry.add('treeMany2OneAllOpen', TreeMany2One_all_open);
    fieldRegistry.add('treeMany2OneList', TreeMany2One_list);

});